'use strict';

angular
  .module('cmsysApp')
  .service(
    'userService',
    [
      '$http',
      'pageService',
      'baseService',
      function ($http, pageService, baseService) {
        var self = this;
        this.allRoles = function ($scope) {
          baseService.query({'url': baseUrl + '/role/roleList'}).then(function (data) {
            $scope.roles = data.roles;
          });
        };
        this.del = function (username) {
          baseService.del({'url': baseUrl + '/user/delUser', 'params': {'username': username}})
        };
        this.userList = function ($scope) {
          self.params = $scope.params || {};
          pageService.query($scope.params).then(function (page) {
            pageService.loadData($scope, page);
          });
        };
        this.addUser = function () {
          baseService.query({'url': baseUrl + '/user/addUser'});
        };
        this.updateUser = function (user) {
          baseService.edit({'url': baseUrl + '/user/updateUser', 'params': user})
        };
      }])
  .controller(
    'userCtrl',
    ['$scope', '$http', '$state', '$stateParams', 'userService', 'pageService', 'userPrivileges',
      function ($scope, $http, $state, $stateParams, userService,pageService, userPrivileges) {
        $scope.opt = userPrivileges['删除用户'] || userPrivileges['设置用户角色'];
        $scope.params = {
          'url': baseUrl + '/user/userList',
          'conditions': {
            'condition': '',
            'currentPage': 1,
            'pageSize': 10
          }
        };
        userService.userList($scope);
        userService.allRoles($scope);
        $scope.del = function (username) {
          userService.del(username);
          userService.userList($scope);
        };
        $scope.loadData = function (page) {
          pageService.loadData($scope, page);
        }

        $scope.changePS = function () {
          pageService.changePS($scope);
          userService.userList($scope);
        };
        $scope.changeCD = function () {
          pageService.changeCD($scope);
          userService.userList($scope);
        };
        $scope.go = function (pageNum) {
          $scope.params.conditions.currentPage = pageNum;
          userService.userList($scope);
        }
        $scope.users = [{
          'username': '数据加载中。。。',
        }];

        $scope.addUser = function () {
          userService.addUser();
          userService.userList($scope);
        };
        $scope.edit = function (index) {
          userService.user = $scope.page.recordList[index];
          $scope.rid = userService.user.rid + "";
          $('#user').modal('toggle');
        };
        $scope.save = function () {
          var user = {};
          user.rid = $scope.rid;
          user.id = userService.user.id;
          userService.updateUser(user);
          $('#user').modal('toggle');
          userService.userList($scope);
        };
      }]);
